package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateGetVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.webdetail.pojo.dto.WorkReportTargetThroughDTO;
import com.xbongbong.pro.webdetail.pojo.vo.WorkReportDetailVO;
import com.xbongbong.pro.webdetail.pojo.vo.WorkReportTargetThroughVO;
import com.xbongbong.pro.weblist.pojo.dto.WorkReportListDTO;
import com.xbongbong.pro.weblist.pojo.dto.WorkReportStatisicDTO;
import com.xbongbong.pro.weblist.pojo.dto.WorkReportUserStatisicDTO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportStatisicVO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportUserStatisicVO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportVO;
import com.xbongbong.pro.weblist.pojo.vo.WorkReportVisibleRangeVO;
import com.xbongbong.pro.workreport.pojo.dto.WorkReportPushRemindDTO;
import com.xbongbong.pro.workreport.pojo.vo.WorkReportPushRemindVO;
import com.xbongbong.saas.service.WorkReportService;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/2/13 10:14
 * @since v1.0
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/workReport")
public class WorkReportController {

    @Resource
    private WorkReportService workReportService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private PaasFormModel paasFormModel;

    /**
     * 新建表单数据（需要返回表单字段描述）
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/add/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addGet(@RequestBody @Valid FormDataAddGetDTO formDataAddGetDTO, BindingResult br) {
        XbbResponse<FormDataAddGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(formDataAddGetDTO.getSaasMark(), formDataAddGetDTO.getBusinessType(), formDataAddGetDTO.getMenuId(), formDataAddGetDTO.getDistributorMark());
                PaasFormDataEntityExt workReportEntity = workReportService.getWorkReport(formDataAddGetDTO);
                Long workReportId = workReportEntity.getId();
                formDataAddGetDTO.setFormId(workReportEntity.getFormId());
                if (workReportId != null && workReportId > 0) {
                    FormDataUpdateGetDTO formDataUpdateGetDTO = new FormDataUpdateGetDTO();
                    BeanUtil.copyProperties(formDataAddGetDTO, formDataUpdateGetDTO);
                    formDataUpdateGetDTO.setDataId(workReportId);
                    return workReportUpdateGet(formDataUpdateGetDTO);
                } else {
                    FormDataAddGetVO formDataAddGetVO = paasFormDataService.addGet(formDataAddGetDTO);
                    response = new XbbResponse<>(formDataAddGetVO);
                }

            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 新建表单数据（需要返回表单字段描述）
     * @param
     * @param br
     * @return
     */
    @RequestMapping(value = "/update/get", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateGet(@RequestBody @Valid FormDataUpdateGetDTO formDataUpdateGetDTO, BindingResult br) {
        XbbResponse<FormDataUpdateGetVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(formDataUpdateGetDTO.getSaasMark(), formDataUpdateGetDTO.getBusinessType(), formDataUpdateGetDTO.getMenuId(), formDataUpdateGetDTO.getDistributorMark());
                Long menuId = formDataUpdateGetDTO.getMenuId();
                String corpid = formDataUpdateGetDTO.getCorpid();
                Integer businessType = formDataUpdateGetDTO.getBusinessType();
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByMenuIdAndBusinessType(menuId.intValue(), corpid, businessType);
                Long formId = paasFormEntityExt.getId();
                formDataUpdateGetDTO.setFormId(formId);
                FormDataUpdateGetVO formDataUpdateGetVO = paasFormDataService.updateGet(formDataUpdateGetDTO);
                response = new XbbResponse<>(formDataUpdateGetVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 工作报告更新，折中处理一下，期待更优解
     * @param formDataUpdateGetDTO 更新参数
     * @return
     */
    private String workReportUpdateGet(FormDataUpdateGetDTO formDataUpdateGetDTO) {
        XbbResponse<FormDataUpdateGetVO> response;
        try {
            FormDataUpdateGetVO formDataUpdateGetVO = paasFormDataService.updateGet(formDataUpdateGetDTO);
            response = new XbbResponse<>(formDataUpdateGetVO);
        } catch (XbbException e) {
            response = new XbbResponse<>(e);
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 工作报告列表统计
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/statisticsList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String statisticsList(@RequestBody @Valid WorkReportStatisicDTO workReportStatisicDTO, BindingResult br) {
        XbbResponse<WorkReportStatisicVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportStatisicVO workReportStatisicVO = workReportService.statisticsList(workReportStatisicDTO);
                response = new XbbResponse<>(workReportStatisicVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 工作报告列表统计穿透
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/detail", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String detail(@RequestBody @Valid FormDataGetDTO formDataGetDTO, BindingResult br) {
        XbbResponse<WorkReportDetailVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportDetailVO workReportDetailVO = workReportService.detail(formDataGetDTO);
                response = new XbbResponse<>(workReportDetailVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 工作报告未读消息提醒
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/message/remind", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String messageRemind(@RequestBody @Valid FormDataGetDTO formDataGetDTO, BindingResult br) {
        XbbResponse<WorkReportPushRemindVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportPushRemindVO workReportPushRemindVO = workReportService.messageRemind(formDataGetDTO);
                response = new XbbResponse<>(workReportPushRemindVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 工作报告详情
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/userStatisticsList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String userStatisticsList(@RequestBody @Valid WorkReportUserStatisicDTO workReportUserStatisicDTO, BindingResult br) {
        XbbResponse<WorkReportUserStatisicVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportUserStatisicVO workReportUserStatisicVO = workReportService.userStatisticsList(workReportUserStatisicDTO);
                response = new XbbResponse<>(workReportUserStatisicVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 工作报告
     * @param br BindingResult
     * @return String
     */
    @RequestMapping(value = "/visibleRange", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String visibleRange(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<WorkReportVisibleRangeVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportVisibleRangeVO workReportUserStatisicVO = workReportService.visibleRange(baseDTO);
                response = new XbbResponse<>(workReportUserStatisicVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取工作报告数据列表
     * @param workReportListDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String workReportList(@RequestBody @Valid WorkReportListDTO workReportListDTO, BindingResult br) {
        XbbResponse<WorkReportVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(workReportListDTO.getSaasMark(), workReportListDTO.getBusinessType(), null, workReportListDTO.getDistributorMark());
                WorkReportVO workReportVO = workReportService.workReportList(workReportListDTO);
                response = new XbbResponse<>(workReportVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 获取工作报告数据列表
     * @param workReportTargetThroughDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/targetThrough", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String targetThrough(@RequestBody @Valid WorkReportTargetThroughDTO workReportTargetThroughDTO, BindingResult br) {
        XbbResponse<WorkReportTargetThroughVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportTargetThroughVO workReportTargetThroughVO = workReportService.targetThrough(workReportTargetThroughDTO);
                response = new XbbResponse<>(workReportTargetThroughVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 一键提醒发送报告
     *
     * @param workReportPushRemindDTO
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-11-13 20:48
     * @since
     * @version
     */
    @RequestMapping(value = "/pushToAllNotSent", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String pushToAllNotSent(@RequestBody @Valid WorkReportPushRemindDTO workReportPushRemindDTO, BindingResult br) {
        XbbResponse<WorkReportPushRemindVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                WorkReportPushRemindVO workReportPushRemindVO = workReportService.pushToAllNotSent(workReportPushRemindDTO);
                response = new XbbResponse<>(workReportPushRemindVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
